#pragma once

#include <iostream>
#include <pthread.h>
#include <functional>
#include "Socket.hpp"
using namespace std;

const int defaultbacklog = 5;
using task_t = function<string(string &)>;

class TcpServer;
class ThreadData
{
public:
    ThreadData(TcpServer *obj_ptr, Socket *sock) : _this(obj_ptr), _sock(sock)
    {
    }

    TcpServer *_this;
    Socket *_sock;
};

class TcpServer
{
private:
    static void *ThreadRun(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        string message;
        // 1. 收网络消息
        td->_sock->Recv(message, 4096);
        // 2. 让ServerHandler处理网络信息
        string response = td->_this->_func(message);
        // 3. 发送响应
        td->_sock->Send(response);
        sleep(1);

        td->_sock->CloseSockFd();
        delete td->_sock;
        delete td;
        return nullptr;
    }

public:
    TcpServer(int port, task_t func) : _port(port), _func(func)
    {
        _listen = new TcpSocket();
        _listen->BuildListenSocket(port, defaultbacklog);
    }

    void Loop()
    {
        for (;;)
        {
            string clientip;
            uint16_t clientport;
            Socket *newsock = _listen->BuildServerSocket(&clientip, &clientport);
            if (newsock != nullptr)
            {
                // 创建新连接成功，将新连接的服务给新线程去做，主线程继续等待新连接
                pthread_t tid;
                ThreadData *td = new ThreadData(this, newsock);
                pthread_create(&tid, nullptr, ThreadRun, td);
            }
        }
    }

    ~TcpServer()
    {
        delete _listen;
    }

private:
    task_t _func;

    Socket *_listen;
    uint16_t _port;
};
